<?php
/**
 * @file name : filetemplate_model.php
 * @package   :
 * @author    : Vo Thanh Minh
 * @email     : <thanhminhld@yahoo.com - thanhminhld@gmail.com>
 * @copyright : 2011
 *
 */
if (!defined('BASEPATH')) {
    exit('No direct script access');
}

class Filetemplate_model extends Base_Model
{
    /**
     * @function __construct
     * @author   Vo Thanh Minh <thanhminhld@yahoo.com - thanhminhld@gmail.com>
     */
    public function __construct()
    {
        parent::__construct();
    }
    /**
     * @function createTemplateModules
     *
     * @author   Vo Thanh Minh <thanhminhld@yahoo.com - thanhminhld@gmail.com>
     * @access   public
     * @param     boolean
     * @param     array
     * @param     string
     * @return
     */
    public function createTemplateModules(&$errCode, $arrModule = array(), $projectName)
    {
        $errCode = FALSE;
        // set permission templates folder
        $outPut = array();
        exec('chmod -R 0777 ' . PROJECT_PATH . $projectName . '/administrator/application/templates', $outPut);
        if (count($outPut) > 0) {
            foreach ($outPut as $k => $err) {
                $this->messages->add($err, 'error');
            }
            $errCode = TRUE;
            return false;
        }
        foreach ($arrModule as $key => $module) {
            if ( ! is_null($module->m_tbl_name) && strlen($module->m_tbl_name) > 0) {
                // Create manage file
                $this->createManageFile($errCode, $projectName, $module);

            } else {
                // for child module template
                $arrWhere = array($module->m_id);
                $arrChildModule = $this->modules_model->loadListIn('parent_id', $arrWhere);
                foreach ($arrChildModule as $childKey => $childModule) {
                    if (! is_null($childModule->m_tbl_name) && strlen($childModule->m_tbl_name) > 0) {
                        // Create manage file
                        $this->createManageFile($errCode, $projectName, $childModule);
                    }
                }
            }
        }
    }
    /**
     * @function createManageFile
     *
     * @author   Vo Thanh Minh <thanhminhld@yahoo.com - thanhminhld@gmail.com>
     * @access   private
     * @param     array
     * @param     string
     * @param     object
     * @return     boolean
     */
    private function createManageFile(&$errCode, $projectName, $moduleObj)
    {
        if ( ! is_object($moduleObj)) {
            return false;
        }
        $controlName = preg_replace('/_/', '', $moduleObj->m_name);
        // Create control folder
        exec('mkdir --mode=0775 ' . PROJECT_PATH . $projectName . '/administrator/application/templates/' . $controlName, $outPut);
        if (count($outPut) > 0) {
            foreach ($outPut as $k => $err) {
                $this->messages->add($err, 'error');
            }
            $errCode = TRUE;
            return false;
        }
        if ($errCode == TRUE) {
            return false;
        }
        if ($moduleObj->m_template_add == 'N' && $moduleObj->m_template_edit == 'Y') {
            $filename         = APPPATH . 'tem_default/add_edit_only.php';
            $filename_addedit = '';
        } else {
            // Doc file template phu hop theo tung module
            $filename         = APPPATH . 'tem_default/manage.php';
            $filename_addedit = APPPATH . 'tem_default/addedit.php';
        }
        $fp = fopen($filename, 'r');
        $buffer = '';
        if ($fp) {
            while ( ! feof($fp)) {
                $buffer .= fgets($fp);
            }
        }
        fclose($fp);
        // Lay noi dung file template cho truong hop module co them chuc nang them,sua~ (ngoai chuc nang quan ly)
        $buff_addedit = '';
        if ($filename_addedit != '' && file_exists($filename_addedit)) {
            $fp = fopen($filename_addedit, 'r');
            if ($fp) {
                while ( ! feof($fp)) {
                    $buff_addedit .= fgets($fp);
                }
            }
            fclose($fp);
        }
        // Tao file quan ly
        if (strlen($buffer) > 0) {
            $arrReplace = array('\<TPL_MODULE_VIEW\>' => $moduleObj->m_name_view,
                                '\<TPL_TBL_PRI_ID\>'  => $moduleObj->tbl_pri_id,
                                '\<FIELD_NAME\>'      => $moduleObj->tbl_pri_name,
                                '\<TBL_PRARENT_ID\>'  => $moduleObj->tbl_parent_id);

            // Manage recursive category
            if ($moduleObj->m_recursive == 'Y') {
                $strJs = '/**' . "\n"
                       . '     * expendChild"' . "\n"
                       . '    */' . "\n"
                       . '    function expendChild(id)' . "\n"
                       . '    {ldelim}' . "\n"
                       . '        '
                       . 'if (document.getElementById(id).style.display == \'none\') {ldelim}' . "\n"
                       . '            '
                       . '$(\'#\' + id).show();' . "\n"
                       . '        '
                       . '{rdelim} else {ldelim}' . "\n"
                       . '            '
                       . '$(\'#\' + id).hide()' . "\n"
                       . '        {rdelim}' . "\n"
                       . '        {rdelim}' . "\n";
                $strIfRecursiveAddEdit = '{if $module->child == 1}' . "\n"
                                       . '					'
                                       . '<li class="iconChild"><a href="javascript:void(0)" onclick="expendChild(\''
                                       . 'R{$module-><TPL_TBL_PRI_ID>}\')">'
                                       . '<img src="{$base_media}/images/selected_tab_arrow.gif" border="0"'
                                       . 'width="9" height="4" name=""></a></li>' . "\n"
                                       . '					{/if}';
                $strRecursiveLoop = '{if $module->child == 1}' . "\n"
                                  . '<tr class="oddRow" id="R{$module-><TPL_TBL_PRI_ID>}" style="display:none;">' . "\n"
                                  . '<td colspan="3">' . "\n"
                                  . '{foreach from=$chidlCategoryList item=childCategory}' . "\n"
                                  . '{if $childCategory-><TBL_PRARENT_ID> == $module-><TPL_TBL_PRI_ID>}' . "\n"
                                  . '<div class="subCategory">{$childCategory-><FIELD_NAME>}</div>' . "\n"
                                  . '<div><input type="button" name="" id="" value="##DEL_ICON##"'
                                  . 'onclick="delFunct(\'{$childCategory-><TPL_TBL_PRI_ID>}\')">&nbsp;'
                                  . '<input type="button" name="" id="" value="##EDIT_ICON##" onclick="editFunct(\''
                                  . '{$childCategory-><TPL_TBL_PRI_ID>}\')"></div>' . "\n"
                                  . '{/if}' . "\n"
                                  . '{/foreach}' . "\n"
                                  . '</td>' . "\n"
                                  . '</tr>' . "\n"
                                  . '{/if}';
                $buffer = preg_replace('/\<JS_RECURSIVE_FUNC\>/', $strJs, $buffer);
                $buffer = preg_replace('/\<IF_RECURSIVE_CHILD_ADD_EDIT\>/', $strIfRecursiveAddEdit, $buffer);
                $buffer = preg_replace('/\<IF_RECURSIVE_CATEGORY\>/', $strRecursiveLoop, $buffer);
            } else {
                $buffer = preg_replace('/\<JS_RECURSIVE_FUNC\>/', '', $buffer);
                $buffer = preg_replace('/\<IF_RECURSIVE_CHILD_ADD_EDIT\>/', '', $buffer);
                $buffer = preg_replace('/\<IF_RECURSIVE_CATEGORY\>/', '', $buffer);
            }
            foreach ($arrReplace as $repKey => $val) {
                $buffer = preg_replace('/' . $repKey . '/', $val, $buffer);
            }
            if ($moduleObj->m_template_add == 'N' && $moduleObj->m_template_edit == 'Y') {
                // Truong hop module khong co chuc nang quan ly
                $filename = PROJECT_PATH . $projectName . '/administrator/application/templates/'
                            . $controlName . '/admin.' . $controlName . '_addedit.tpl';
            } else {
                $filename = PROJECT_PATH . $projectName . '/administrator/application/templates/'
                            . $controlName . '/admin.' . $controlName . '_manage.tpl';
            }

            $fp = fopen($filename, 'w');
            fwrite($fp, $buffer);
            fclose($fp);
        }
        // Tao file them - chinh sua
        //echo $moduleObj->m_name . '--><br>';
        if (strlen($buff_addedit) > 0) {
            if (preg_match('/ckeditor:S|ckeditor:F/', $moduleObj->m_field_info)) {
                $arrReplace = array('\<TPL_MODULE_VIEW\>'   => $moduleObj->m_name_view,
                                    '\<TPL_TBL_PRI_ID\>'    => $moduleObj->tbl_pri_id,
                                    '\<END_DECRIPT_TAG\>'   => '-->',
                                    '\<START_DECRIPT_TAG\>' => '<!--');
            } else {
                $arrReplace = array('\<TPL_MODULE_VIEW\>'   => $moduleObj->m_name_view,
                                    '\<TPL_TBL_PRI_ID\>'    => $moduleObj->tbl_pri_id);
            }
            if ($moduleObj->m_recursive == 'Y') {
                // Replace js function
                $jsRootCategory = '/**' . "\n" . '         * chooseCategory' . "\n" . '         */' . "\n"
                                . '        ' . 'function chooseCategory(val)' . "\n"
                                . '        {ldelim}' . "\n"
                                . '            if (isNaN(val) || val < 0) {ldelim}' . "\n"
                                . '                alert(\'##JS_DATA_INVALID##\');' . "\n"
                                . '                return false;' . "\n"
                                . '            {rdelim}' . "\n"
                                . '            $(\'#parent_category_id\').val(val);' . "\n"
                                . '        {rdelim}';
                $buff_addedit = preg_replace('/\<JS_ROOT_CATEGORY\>/', $jsRootCategory, $buff_addedit);

                $strRootCategoryTpl = '';
                $fpR = fopen(APPPATH . 'tem_default/recursive_category_addedit_tpl.php');
                if ($fpR) {
                    while ( ! feof($fpR)) {
                        $strRootCategoryTpl .= fgets($fpR);
                    }
                }
                fclose($fpR);
                $buff_addedit = preg_replace('/\<ROOT_CATEGORY_TPL\>/', $strRootCategoryTpl, $buff_addedit);

                $strHiddenRootCategory = '<input type="hidden" name="parent_category_id" id="parent_category_id" value="{$currentParentId}"/>';
                $buff_addedit = preg_replace('/\<HIDDEN_ROOT_CATEGORY\>/', $strHiddenRootCategory, $buff_addedit);

            }
            foreach ($arrReplace as $repKey => $val) {
                $buff_addedit = preg_replace('/' . $repKey . '/', $val, $buff_addedit);
            }
            if (strlen($moduleObj->m_field_info) > 0) {
                $arrTmp = explode(';', $moduleObj->m_field_info);
                $filed_info = array();
                foreach ($arrTmp as $fieldInfo) {
                    $arrFieldTmp = explode(',', $fieldInfo);
                    array_push($filed_info, arrayFilter(':', $arrFieldTmp));
                }

                // Get default form contail
                $textCheckBox  = $this->createFormTemplate('checkBox');
                $textField     = $this->createFormTemplate('text');
                $textareaField = $this->createFormTemplate('textarea');
                $fileField     = $this->createFormTemplate('file');
                $areaSimple    = $this->createFormTemplate('areaSimple');
                $areaFull      = $this->createFormTemplate('areaFull');

                $strForm       = '';
                $strFormJs     = '';
                $refixLang     = strtoupper($moduleObj->m_name);
                $strGlobalLang = '';
                foreach ($filed_info as $key => $field) {
                    if ($field['field_type'] == 'CheckBox') {
                        $strForm .= preg_replace('/\<TEXT_FIELD_TITLE\>/', $refixLang . '_TEXT_FIELD_TITLE_' . $key,
                                                 $textField);
                        $strGlobalLang .= $refixLang . '_TEXT_FIELD_TITLE_' . $key . ' = '
                                       .  $field['field_title'] . "\n";
                    }
                    if ($field['field_type'] == 'Text') {
                        $strForm .= preg_replace('/\<TEXT_FIELD_TITLE\>/', $refixLang . '_TEXT_FIELD_TITLE_' . $key,
                                                 $textField);
                        $strForm = preg_replace('/\<FIELD_SIZE\>/', $field['field_size'], $strForm);

                        if ($field['field_size'] == 'smallInput') {
                            $strForm = preg_replace('/\<CLSS_SIZE\>/', '22', $strForm);
                        } else if ($field['field_size'] == 'mediumInput') {
                            $strForm = preg_replace('/\<CLSS_SIZE\>/', '51', $strForm);
                        }
                        $strGlobalLang .= $refixLang . '_TEXT_FIELD_TITLE_' . $key . ' = '
                                       . $field['field_title'] . "\n";
                    }
                    if ($field['field_type'] == 'TextArea') {
                        $strForm .= preg_replace('/\<TEXTAREA_FIELD_TITLE\>/', $refixLang
                                                 . '_TEXTAREA_FIELD_TITLE_' . $key, $textareaField);

                        if (preg_match('/S/', $field['ckeditor'])) {
                            $strFormJs .= preg_replace('/\<FIELD_NAME\>/', $field['field_name'], $areaSimple) . "\n";

                        } else if (preg_match('/F/', $field['ckeditor'])) {
                            $strFormJs .= preg_replace('/\<FIELD_NAME\>/', $field['field_name'], $areaFull) . "\n";
                        }
                        $strGlobalLang .= $refixLang . '_TEXTAREA_FIELD_TITLE_' . $key . ' = '
                                       . $field['field_title'] . "\n";
                    }
                    if ($field['field_type'] == 'File') {
                        $strForm .= preg_replace('/\<FILE_FIELD_TITLE\>/', $refixLang . '_FILE_FIELD_TITLE_' . $key,
                                                 $fileField);
                        $strGlobalLang .= $refixLang . '_FILE_FIELD_TITLE_' . $key . ' = '
                                       . $field['field_title'] . "\n";
                    }
                    $strForm = preg_replace('/\<FIELD_NAME\>/', $field['field_name'], $strForm);
                }
                //burg_array($filed_info); echo '<br>';
                $buff_addedit = preg_replace('/\<FORM_FIELD\>/', $strForm, $buff_addedit);
                $buff_addedit = preg_replace('/\<TEXTARE_JS\>/', $strFormJs, $buff_addedit);
                // Ghi noi dung file lang
                $proj_lang = $this->input->post('proj_lang');
                $proj_lang = substr($proj_lang, 0, -1);
                $proj_lang = explode(',', $proj_lang);

                foreach ($proj_lang as $pLang) {
                    $path = PROJECT_PATH . $projectName . '/administrator/application/language/' . $pLang;
                    $this->project_model->setPermission($errCode, $path, 'global.lng', ' ', '0777');
                    $fpLang = fopen($path . '/global.lng', 'a+');
                    if ($fpLang) {
                        fwrite($fpLang, $strGlobalLang);
                    }
                    fclose($fpLang);
                }
            }
            $filename = PROJECT_PATH . $projectName . '/administrator/application/templates/' . $controlName
                      . '/admin.' . $controlName . '_addedit.tpl';

            $fp = fopen($filename, 'w');
            fwrite($fp, $buff_addedit);
            fclose($fp);
        }
    }
    /**
     * @function createFormTemplate
     *
     * @author     Vo Thanh Minh <thanhminhld@yahoo.com - thanhminhld@gmail.com>
     * @access      private
     * @param     string
     * @return     string
     */
    private function createFormTemplate($formName)
    {
        $fileName = '';
        switch ($formName) {

            case 'checkBox':
                $fileName = 'check_box_form.php';
                break;

            case 'text':
                $fileName = 'text_form.php';
                break;

            case 'textarea':
                $fileName = 'textarea_form.php';
                break;

            case 'file':
                $fileName = 'file_form.php';
                break;

            case 'areaSimple':
                $fileName = 'textarea_js_simple.php';
                break;

            case 'areaFull':
                $fileName = 'textarea_js_full.php';
                break;
        }
        if ($fileName == '') {
            return $fileName;
        }
        $fileName = APPPATH . 'tem_default/' . $fileName;
        $strForm = '';
        if (file_exists($fileName)) {
            $fp = fopen($fileName, 'r');
            if ($fp) {
                while ( ! feof($fp)) {
                    $strForm .= fgets($fp);
                }
            }
            fclose($fp);
        }
        return $strForm;
    }
}